package com.example.pictureview.widget;

import android.content.Context;
import android.content.res.Configuration;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.pictureview.R;

import java.util.Formatter;
import java.util.Locale;

import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;

/**
 * Created by Administrator on 2017/7/26 0026.
 */

public class MediaControllerView extends MediaController {
    private final static String TAG = "MediaControllerView";
    private static final int sDefaultTimeout = 3000;
    MediaPlayerControl mPlayer;
    Formatter mFormatter;
    StringBuilder mFormatBuilder;
    private boolean mDragging;

    public MediaControllerView(Context context) {
        this(context, null);
    }

    public MediaControllerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mRoot = this;
    }


    private boolean mShowing = false;
    private View mRoot;


    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        if (mRoot != null) {
            initControllerView(mRoot);
        }

    }


    @Override
    public void hide() {
        Log.i(TAG, "##hide");
        if (mShowing) {
            removeCallbacks(mShowProgress);
            removeCallbacks(mFadeOut);
            setVisibility(GONE);
            mShowing = false;
        }
    }

    @Override
    public boolean isShowing() {
        Log.i(TAG, "##isShowing");
        return mShowing;
    }

    private View mAnchor;

    @Override
    public void setAnchorView(View view) {
        Log.i(TAG, "##setAnchorView:" + view);

        mAnchor = view;
//        try {

        ViewGroup.LayoutParams frameParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        LinearLayout.LayoutParams linearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        removeAllViews();
        View v = makeControllerView();
        addView(v, frameParams);
//        ((ViewGroup) view).addView(this, new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }


//    public static RelativeLayout.LayoutParams getControllerLayoutParams(Context context, VideoView videoView, boolean portrait) {
//        RelativeLayout.LayoutParams controlLayout = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        if (portrait) {
//
//            controlLayout.addRule(RelativeLayout.ALIGN_BOTTOM, videoView.getId());
//        } else {
//
//            controlLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
//        }
//
//        return controlLayout;
//    }


    private View makeControllerView() {
        mRoot = View.inflate(getContext(), R.layout.include_media_control, null);
        initControllerView(mRoot);
        return mRoot;
    }

    @Override
    protected void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mFullButton != null) {
            if (newConfig.orientation == SCREEN_ORIENTATION_PORTRAIT) {
                mFullButton.setImageResource(R.drawable.video_full_screen);
            } else {
                mFullButton.setImageResource(R.drawable.video_half_screen);
            }

        }
    }

    private ImageView mPauseButton, mFullButton;
    private SeekBar mProgress;
    private TextView mEndTime, mCurrentTime;

    private void initControllerView(View v) {
        mPauseButton = (ImageView) v.findViewById(R.id.button_media_control);
        if (mPauseButton != null) {
            mPauseButton.setOnClickListener(mPauseListener);
        }
        mFullButton = (ImageView) v.findViewById(R.id.button_media_control_full_screen);
        if (mFullButton != null) {
            mFullButton.setOnClickListener(mFullListener);
        }
        mProgress = (SeekBar) v.findViewById(R.id.seekbar_media_control);
        if (mProgress != null) {
            mProgress.setMax(1000);
            mProgress.setOnSeekBarChangeListener(mSeekListener);
        }
        mEndTime = (TextView) v.findViewById(R.id.textview_media_control_end_time);
        mCurrentTime = (TextView) v.findViewById(R.id.textview_media_control_current_time);
        mFormatBuilder = new StringBuilder();
        mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

        if (!mShowing) {
            setVisibility(GONE);
        } else {
            setVisibility(VISIBLE);
        }

//        setVisibility(GONE);
    }

    private final OnClickListener mPauseListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            doPauseResume();
            show(sDefaultTimeout);
        }
    };
    private OnClickListener mFullListener = null;

    public void setOnFullListener(OnClickListener clickListener) {
        mFullListener = clickListener;
        if (mFullButton != null) {
            mFullButton.setOnClickListener(mFullListener);
        }
    }

    private void doPauseResume() {
        if (mPlayer.isPlaying()) {
            mPlayer.pause();
        } else {
            mPlayer.start();
        }


        updatePausePlay();
    }

    private final SeekBar.OnSeekBarChangeListener mSeekListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStartTrackingTouch(SeekBar bar) {

            Log.i(TAG, "###onStartTrackingTouch");

            show(3600000);

            mDragging = true;

            removeCallbacks(mShowProgress);
        }

        @Override
        public void onProgressChanged(SeekBar bar, int progress, boolean fromuser) {
            Log.i(TAG, "###onProgressChanged:" + fromuser);
            if (!fromuser) {

                return;
            }

            long duration = mPlayer.getDuration();
            long newposition = (duration * progress) / 1000L;
            mPlayer.seekTo((int) newposition);
            if (mCurrentTime != null)
                mCurrentTime.setText(stringForTime((int) newposition));
        }

        @Override
        public void onStopTrackingTouch(SeekBar bar) {
            Log.i(TAG, "###onStopTrackingTouch");
            mDragging = false;
            setProgress();
            updatePausePlay();
            show(sDefaultTimeout);

            // Ensure that progress is properly updated in the future,
            // the call to show() does not guarantee this because it is a
            // no-op if we are already showing.
            post(mShowProgress);
        }
    };

    private final Runnable mShowProgress = new Runnable() {
        @Override
        public void run() {
            int pos = setProgress();
            if (!mDragging && mShowing && mPlayer.isPlaying()) {
                postDelayed(mShowProgress, 1000 - (pos % 1000));
            }
        }
    };

    @Override
    public void setMediaPlayer(MediaPlayerControl player) {
        Log.i(TAG, "##setMediaPlayer");
        mPlayer = player;
        updatePausePlay();
    }

    private void updatePausePlay() {
        if (mPauseButton == null)
            return;

        Log.i(TAG, "##isPlaying:" + mPlayer.isPlaying());

        if (mPlayer.isPlaying()) {
            mPauseButton.setImageResource(R.drawable.video_pause);
        } else {
            mPauseButton.setImageResource(R.drawable.video_playing);
        }
    }

    @Override
    public void show(int timeout) {
        Log.i(TAG, "##show:" + timeout);

        if (!mShowing && mAnchor != null) {
            setProgress();
//            disableUnsupportedButtons();
            setVisibility(VISIBLE);
            mShowing = true;
        }
        updatePausePlay();
        post(mShowProgress);

        if (timeout != 0) {
            removeCallbacks(mFadeOut);
            postDelayed(mFadeOut, timeout);
        }
    }

    private final Runnable mFadeOut = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    @Override
    public void setEnabled(boolean enabled) {
        Log.i(TAG, "##setEnabled:" + enabled);

        if (mPauseButton != null) {
            mPauseButton.setEnabled(enabled);
        }

        if (mProgress != null) {
            mProgress.setEnabled(enabled);
        }
//        disableUnsupportedButtons();
        super.setEnabled(enabled);
    }

//    private void disableUnsupportedButtons() {
//        try {
//            if (mPauseButton != null && !mPlayer.canPause()) {
//                mPauseButton.setEnabled(false);
//            }
//
//            if (mProgress != null && !mPlayer.canSeekBackward() && !mPlayer.canSeekForward()) {
//                mProgress.setEnabled(false);
//            }
//        } catch (IncompatibleClassChangeError ex) {
//
//        }
//    }

    @Override
    public void show() {
        Log.i(TAG, "##show");
        show(sDefaultTimeout);
    }

    private int setProgress() {
        if (mPlayer == null || mDragging) {
            return 0;
        }
        int position = mPlayer.getCurrentPosition();
        int duration = mPlayer.getDuration();
        if (mProgress != null) {
            if (duration > 0) {
                // use long to avoid overflow
                long pos = 1000L * position / duration;
                mProgress.setProgress((int) pos);
            }
            int percent = mPlayer.getBufferPercentage();
            mProgress.setSecondaryProgress(percent * 10);
        }

        if (mEndTime != null)
            mEndTime.setText(stringForTime(duration));
        if (mCurrentTime != null)
            mCurrentTime.setText(stringForTime(position));

        return position;
    }

    private String stringForTime(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        mFormatBuilder.setLength(0);
        if (hours > 0) {
            return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return mFormatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }


}
